package main

import (
	"fileHandler/filelist"
	"log"
	"net/http"
	"os"
)

func openFile(path string){

}

type appHandler func (writer http.ResponseWriter, request *http.Request) error

func errWrapper (handler appHandler) func(http.ResponseWriter, *http.Request) {
	return  func(writer http.ResponseWriter, requst *http.Request) {
		err := handler(writer, requst)
		defer func() {
			if r := recover(); r != nil {
				log.Printf( "panic : %v", r)
				http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()

		if err != nil {
			log.Printf("Error is occurred ! handler requset err: %v", err.Error())
			code := http.StatusOK
			if userErr, ok := err.(userError);ok {
				http.Error(
					writer,
					userErr.Message(),
					http.StatusInternalServerError)
				return
			}
			switch {
			case os.IsNotExist(err):
				code = http.StatusNotFound
			case os.IsPermission(err):
				code = http.StatusForbidden
			default:
				code = http.StatusInternalServerError
			}
			http.Error(writer, http.StatusText(code), code)
		}
	}
}

type userError interface {
	error
	Message() string
}

func main(){
	http.HandleFunc("/", errWrapper(filelist.FileHandlerList))
	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		panic(err.Error())
	}
}